<template>
  <div class="review-list-container">

    <a-page-header class="demo-page-header" style="border: 1px solid rgb(235, 237, 240); margin-bottom: 24px;"
      title="案件列表" :sub-title="`${casesData.length}条数据`" @back="() => $router.go(-1)">
      <p class="date-range-info">
        显示所有案件数据，今日和昨日案件已用不同颜色标识
      </p>
      <div class="color-legend">
        <span class="legend-item">
          <span class="legend-color today-pending-audit-color"></span>
          今日待审核案件
        </span>
        <span class="legend-item">
          <span class="legend-color today-color"></span>
          今日案件
        </span>
        <span class="legend-item">
          <span class="legend-color yesterday-color"></span>
          昨日案件
        </span>
        <span class="legend-item">
          <span class="legend-color recent-color"></span>
          近3日案件
        </span>
        <span class="legend-item">
          <span class="legend-color older-color"></span>
          更早案件
        </span>
      </div>

      <template #extra>
        <a-button type="primary" @click="handleRefresh">
          刷新
        </a-button>
      </template>

    </a-page-header>


    <div class="table-section">
      <div class="table-wrapper">
        <Spin :spinning="loading" tip="加载中...">
          <a-tabs v-model:activeKey="activeTabKey" @change="handleTabChange" class="status-tabs">
            <a-tab-pane key="all" tab="全部">
              <a-table :bordered="true" :columns="columns" :data-source="casesData" :pagination="paginationConfig"
                :onChange="handleTableChange" :rowClassName="getRowClassName" row-key="id">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'operation'">
                    <a-space>
                      <a-button v-if="record.state.code !== 'AUDIT_SUCCESS'" size="small" type="link"
                        @click="handleView(record)" 
                        :class="['view-audit-btn', { 'viewed': buttonStates[record.id]?.viewed }]">
                        查看/审核
                      </a-button>
                      <a-button size="small" v-if="record.preAuditFile" type="link"
                        @click="() => handleDownloadSummary(record)" 
                        :class="['download-summary-btn', { 'downloaded': buttonStates[record.id]?.downloaded }]">
                        <span>下载摘要</span>
                      </a-button>
                      <a-button size="small" type="link" @click="() => handleCaseDetail(record)">
                        <span>案件详情</span>
                      </a-button>
                    </a-space>
                  </template>
                  <template v-else-if="column.key === 'state'">
                    <a-tag :color="getStatusColor(record.state)">{{ getStatusText(record.state) }}</a-tag>
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
            <a-tab-pane key="pending" tab="待审核">
              <a-table :bordered="true" :columns="columns" :data-source="filteredCasesData"
                :pagination="paginationConfig" :onChange="handleTableChange" :rowClassName="getRowClassName"
                row-key="id">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'operation'">
                    <a-space>
                      <a-button v-if="record.state.code !== 'AUDIT_SUCCESS'" size="small" type="link"
                        @click="handleView(record)" 
                        :class="['view-audit-btn', { 'viewed': buttonStates[record.id]?.viewed }]">
                        查看/审核
                      </a-button>
                      <a-button size="small" v-if="record.preAuditFile" type="link"
                        @click="() => handleDownloadSummary(record)" 
                        :class="['download-summary-btn', { 'downloaded': buttonStates[record.id]?.downloaded }]">
                        <span>下载摘要</span>
                      </a-button>
                      <a-button size="small" type="primary" @click="() => handleCaseDetail(record)">
                        <span>案件详情</span>
                      </a-button>
                    </a-space>
                  </template>
                  <template v-else-if="column.key === 'state'">
                    <a-tag :color="getStatusColor(record.state)">{{ getStatusText(record.state) }}</a-tag>
                  </template>
                </template>
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </Spin>
      </div>
    </div>

    <!-- 案件详情弹框 -->
    <a-modal v-model:open="caseDetailVisible" title="案件详情" :width="1200" :footer="null"
      @cancel="caseDetailVisible = false">
      <div class="case-detail-modal">
        <div class="user-list">
          <Spin :spinning="caseDetailLoading" tip="加载中...">
            <a-table :columns="caseDetailColumns" :data-source="caseDetailData" :pagination="false"
              :scroll="{ x: 1000 }" :bordered="true" row-key="id" size="small" />
          </Spin>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, h, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message, Modal, Spin } from 'ant-design-vue';
import { getReviewList, getReviewCaseDetail, CASE_STATUS } from '../server/api';
import type { GetReviewListParams, GetReviewUserParams, ReviewUserItem } from '../server/type';
import { useUserStore } from '../store/user';
import dayjs from 'dayjs';

const router = useRouter();
const userStore = useUserStore();

// 分页配置
const paginationConfig = ref({
  current: 1,
  pageSize: 20,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
  pageSizeOptions: ['10', '20', '50', '100']
});

// 表格列配置
const columns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    customRender: ({ index }: { index: number }) => {
      return (paginationConfig.value.current - 1) * paginationConfig.value.pageSize + index + 1;
    }
  },
  {
    title: '委案ID',
    dataIndex: 'id',
    key: 'id',
    width: 120,
    align: 'center',
    customRender: ({ text }: { text: string }) => {
      return text || '-';
    }
  },
  {
    title: '委托方/机构',
    dataIndex: 'entrustBName',
    key: 'entrustBName',
    width: 120,
    align: 'center'
  },
  {
    title: '批次名称',
    dataIndex: 'batchName',
    key: 'batchName',
    width: 200,
    align: 'center',
    customCell: (record: any) => {
      const formattedBatchName = formatBatchName(record.batchName || '');
      return {
        innerHTML: `
          <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
            <span title="${record.batchName || ''}">${formattedBatchName}</span>
            <button 
              class="copy-batch-name-btn" 
              data-batch-name="${record.batchName || ''}"
              style="
                background: none; 
                border: none; 
                cursor: pointer; 
                padding: 2px; 
                border-radius: 4px;
                display: flex;
                align-items: center;
                justify-content: center;
                transition: background-color 0.2s;
              "
              onmouseover="this.style.backgroundColor='#f0f0f0'"
              onmouseout="this.style.backgroundColor='transparent'"
              title="复制批次名称"
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
                <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
              </svg>
            </button>
          </div>
        `
      };
    }
  },
  {
    title: '渠道',
    dataIndex: 'bizChannel',
    key: 'bizChannel',
    width: 120,
    align: 'center'
  },
  {
    title: '产品类型',
    dataIndex: 'productTypeName',
    key: 'productTypeName',
    width: 120,
    align: 'center'
  },
  {
    title: '委案日期',
    dataIndex: 'delegateDate',
    key: 'delegateDate',
    align: 'center',
    width: 110,
    customRender: ({ text }: { text: number }) => {
      return text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : '-';
    }
  },
  {
    title: '案件数量',
    key: 'caseCount',
    align: 'center',
    width: 200,
    customRender: ({ record }: { record: any }) => {
      return h('div', { class: 'case-count-info' }, [
        h('div', { class: 'count-item' }, `总数量：${record.totalCount || 0}`),
        h('div', { class: 'count-item' }, `成功数量：${record.successCount || 0}`),
        h('div', { class: 'count-item' }, `失败数量：${record.failCount || 0}`)
      ]);
    }
  },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    width: 100,
    align: 'center'
  },
  {
    title: '操作',
    key: 'operation',
    fixed: 'right',
    align: 'center',
    width: 160
  }
];

// 案件数据
const casesData = ref<Array<Record<string, any>>>([]);

// 选项卡状态
const activeTabKey = ref('all');

// 按钮状态管理
const buttonStates = ref<Record<string, { viewed: boolean; downloaded: boolean }>>({});

// 加载状态
const loading = ref(false);

// 调试模式（可以通过环境变量控制）
const debugMode = ref(import.meta.env.DEV);

// 过滤统计信息
const filterStats = ref({
  total: 0,
  filtered: 0
});

// 过滤后的案件数据（待审核）
const filteredCasesData = computed(() => {
  if (activeTabKey.value === 'pending') {
    return casesData.value.filter(record => {
      const statusCode = getStatusCode(record.state);
      return isPendingAuditStatus(statusCode);
    });
  }
  return casesData.value;
});


// 获取状态文本
const getStatusText = (status: any) => {
  if (typeof status === 'object' && status.message) {
    return status.message;
  }
  return typeof status === 'string' ? status : '未知';
};

// 获取状态颜色
const getStatusColor = (status: any) => {
  let statusCode = status;
  if (typeof status === 'object' && status.code) {
    statusCode = status.code;
  }
  const colorMap: Record<string, string> = {
    'TO_AUDIT': 'orange',
    'AUDITING': 'processing',
    'AUDIT_SUCCESS': 'success',
    'AUDIT_FAIL': 'error',
    'PRE_AUDIT_FAILED': 'red',
    'PENDING': 'blue',
    'COMPLETED': 'green'
  };
  return colorMap[statusCode] || 'default';
};

// 获取状态码
const getStatusCode = (status: any) => {
  if (typeof status === 'object' && status.code) {
    return status.code;
  }
  return typeof status === 'string' ? status : '';
};

// 判断是否为待审核状态
const isPendingAuditStatus = (statusCode: string) => {
  const pendingStatuses = ['TO_AUDIT', 'AUDITING', 'PENDING'];
  return pendingStatuses.includes(statusCode);
};

// 获取行样式类名
const getRowClassName = (record: any) => {
  if (!record.delegateDate) {
    return 'no-date-row';
  }

  // 解析委案日期
  let delegateDate = dayjs(record.delegateDate);

  // 如果第一次解析失败，尝试其他常见格式
  if (!delegateDate.isValid()) {
    // 尝试解析时间戳（毫秒）
    if (typeof record.delegateDate === 'number') {
      delegateDate = dayjs(record.delegateDate);
    }
    // 尝试解析时间戳（秒）
    else if (typeof record.delegateDate === 'string' && /^\d+$/.test(record.delegateDate)) {
      delegateDate = dayjs(parseInt(record.delegateDate) * 1000);
    }
    // 尝试其他日期格式
    else {
      delegateDate = dayjs(record.delegateDate, ['YYYY-MM-DD', 'YYYY-MM-DD HH:mm:ss', 'YYYY/MM/DD', 'MM/DD/YYYY']);
    }
  }

  // 检查日期是否有效
  if (!delegateDate.isValid()) {
    return 'invalid-date-row';
  }

  const today = dayjs();
  const yesterday = today.subtract(1, 'day');
  const twoDaysAgo = today.subtract(2, 'day');

  // 判断案件日期
  if (delegateDate.isSame(today, 'day')) {
    // 今日案件：检查是否为待审核状态
    const statusCode = getStatusCode(record.state);
    if (isPendingAuditStatus(statusCode)) {
      return 'today-pending-audit-row';
    }
    return 'today-row';
  } else if (delegateDate.isSame(yesterday, 'day')) {
    return 'yesterday-row';
  } else if (delegateDate.isAfter(twoDaysAgo)) {
    return 'recent-row';
  } else {
    return 'older-row';
  }
};

// 处理分页变化
const handleTableChange = (pagination: any) => {
  paginationConfig.value.current = pagination.current;
  paginationConfig.value.pageSize = pagination.pageSize;
  fetchReviewList();
};

// 获取案件列表数据
const fetchReviewList = async () => {
  loading.value = true;
  try {
    // 构建请求参数，获取所有状态的案件
    const params: GetReviewListParams = {
      channelName: '',
      batchName: '',
      state: '', // 空字符串表示获取所有状态
      current: paginationConfig.value.current,
      size: paginationConfig.value.pageSize
    };

    const result = await getReviewList(params);

    if (result.success && result.result) {
      const { records, total } = result.result;
      const allRecords = records || [];

      casesData.value = allRecords;

      // 更新分页信息
      paginationConfig.value.total = total || 0;

      // 更新过滤统计信息（不再过滤，所以都是0）
      filterStats.value = {
        total: allRecords.length,
        filtered: 0
      };

      if (debugMode.value) {
        console.log('获取案件列表结果:', {
          总记录数: allRecords.length,
          分页信息: paginationConfig.value
        });
      }

      message.success(`获取案件列表成功，共 ${allRecords.length} 条记录`);
    } else {
      message.error('获取案件列表失败');
      casesData.value = [];
    }
  } catch (error) {
    console.error('获取案件列表失败:', error);
    message.error('网络错误，请稍后重试');
    casesData.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理刷新
const handleRefresh = () => {
  fetchReviewList();
};

// 处理选项卡切换
const handleTabChange = (key: string) => {
  activeTabKey.value = key;
  console.log('切换到选项卡:', key);
};

// 案件详情弹框相关状态
const caseDetailVisible = ref(false);
const caseDetailLoading = ref(false);
const caseDetailData = ref<ReviewUserItem[]>([]);
const currentBatchInfo = ref<any>(null);

// 获取案件状态的中文显示和颜色
const getCaseStatusInfo = (statusCode: string) => {
  // 查找匹配的状态
  const statusEntry = Object.values(CASE_STATUS).find(status => status.code === statusCode);

  if (statusEntry) {
    // 根据状态码返回对应的颜色
    const colorMap: Record<string, string> = {
      'TO_AUDIT': 'orange',
      'AUDITING': 'processing',
      'PRE_AUDIT_SUCCESS': 'success',
      'PRE_AUDIT_FAILED': 'error',
      'AUDIT_SUCCESS': 'success',
      'AUDIT_FAILED': 'error',
      'IMPORT_FAILED': 'red',
      'INVALID': 'default'
    };

    return {
      text: statusEntry.message,
      color: colorMap[statusCode] || 'default'
    };
  }

  // 如果没有找到匹配的状态，返回默认值
  return {
    text: statusCode || '未知',
    color: 'default'
  };
};

// 案件详情表格列配置
const caseDetailColumns = [
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    customRender: ({ index }: { index: number }) => index + 1
  },
  {
    title: '客户信息',
    key: 'clientInfo',
    width: 200,
    align: 'center',
    customRender: ({ record }: { record: ReviewUserItem }) => {
      return h('div', { class: 'client-info' }, [
        h('div', { class: 'client-name' }, record.clientName || '-'),
        h('div', { class: 'client-mobile' }, record.clientMobile || '-'),
        h('div', { class: 'client-id-card' }, record.clientIdCard || '-')
      ]);
    }
  },
  {
    title: '状态',
    dataIndex: 'state',
    key: 'state',
    width: 120,
    align: 'center',
    customRender: ({ text }: { text: string }) => {
      const statusInfo = getCaseStatusInfo(text);
      return h('a-tag', { color: statusInfo.color }, statusInfo.text);
    }
  },
  {
    title: '贷款产品名称',
    dataIndex: 'loanName',
    key: 'loanName',
    width: 150,
    align: 'center',
    customRender: ({ text }: { text: string }) => text || '-'
  },
  {
    title: '借贷编号',
    dataIndex: 'loanNo',
    key: 'loanNo',
    width: 150,
    align: 'center',
    customRender: ({ text }: { text: string }) => text || '-'
  },
  {
    title: '委托方案件编号',
    dataIndex: 'loanCaseNo',
    key: 'loanCaseNo',
    width: 150,
    align: 'center',
    customRender: ({ text }: { text: string }) => text || '-'
  },
  {
    title: '金融资产',
    key: 'financialAssets',
    width: 200,
    align: 'center',
    customRender: ({ record }: { record: ReviewUserItem }) => {
      return h('div', { class: 'financial-assets' }, [
        h('div', { class: 'delegate-amount' }, `委案金额：${record.loanDelegateAmt || 0}`),
        h('div', { class: 'current-amount' }, `当前应还：${(record.capitalPeriodShouldRepay || 0) + (record.interestPeriodShouldRepay || 0) + (record.feePeriodShouldRepay || 0) + (record.punishPeriodShouldRepay || 0)}`)
      ]);
    }
  }
];

// 处理案件详情
const handleCaseDetail = async (record: any) => {
  try {
    caseDetailVisible.value = true;
    caseDetailLoading.value = true;
    currentBatchInfo.value = record;

    // 调用接口获取案件详情
    const params: GetReviewUserParams = {
      uploadRecordId: record.id,
      clientName: '',
      state: 'INIT',
      current: 1,
      size: 1000, // 获取所有数据，不分页
      tsToken: userStore.tsToken
    };

    const result = await getReviewCaseDetail(params);

    if (result.success && result.result) {
      caseDetailData.value = result.result.records || [];
      message.success(`获取案件详情成功，共 ${caseDetailData.value.length} 条记录`);
    } else {
      message.error('获取案件详情失败');
      caseDetailData.value = [];
    }
  } catch (error) {
    console.error('获取案件详情失败:', error);
    message.error('网络错误，请稍后重试');
    caseDetailData.value = [];
  } finally {
    caseDetailLoading.value = false;
  }
};



// 查看案件详情
const handleView = (record: any) => {
  // 标记为已查看
  if (!buttonStates.value[record.id]) {
    buttonStates.value[record.id] = { viewed: false, downloaded: false };
  }
  buttonStates.value[record.id].viewed = true;
  
  router.push(`/case-detail/${record.id}`);
};

// 删除案件
/**
 * 下载摘要文件
 * @param record 当前行数据，record.preAuditFile 为摘要文件URL
 */
const handleDownloadSummary = (record: any) => {
  if (!record?.preAuditFile) {
    message.error('未找到摘要文件下载地址');
    return;
  }
  Modal.confirm({
    title: '确认下载',
    content: `确定要下载 ${record.batchName} 的摘要吗？`,
    okText: '下载',
    cancelText: '取消',
    async onOk() {
      try {
        // 生成新的文件名
        const newFileName = generateSummaryFileName(record);
        console.log('新的文件名:', newFileName, record);


        // 先获取文件内容，然后重命名下载
        const response = await fetch(record.preAuditFile);
        if (!response.ok) {
          throw new Error('文件下载失败');
        }

        // 获取文件内容
        const blob = await response.blob();

        // 创建新的Blob对象，确保文件名正确
        const newBlob = new Blob([blob], { type: blob.type });

        // 创建下载链接
        const url = window.URL.createObjectURL(newBlob);
        const link = document.createElement('a');
        link.href = url;
        link.download = newFileName;
        link.style.display = 'none';

        // 添加到DOM并触发下载
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        // 标记为已下载
        if (!buttonStates.value[record.id]) {
          buttonStates.value[record.id] = { viewed: false, downloaded: false };
        }
        buttonStates.value[record.id].downloaded = true;
        
        message.success('摘要文件下载成功');
      } catch (error) {
        console.error('下载摘要失败:', error);
        message.error('下载摘要失败，请重试');
      }
    }
  });
};



/**
 * 生成摘要文件名
 * 格式：银行X件调解案-【小时/分钟】.xlsx
 * @param record 案件记录
 * @returns 新的文件名
 */
const generateSummaryFileName = (record: any): string => {
  try {
    const bankName = record.batchName.split('-')[0];
    const caseCount = record.totalCount;
    return `${bankName}${caseCount}件调解案.xlsx`;
  } catch (error) {
    console.error('生成文件名失败:', error);
    // 返回默认文件名
    return `案件摘要_${Date.now()}.xlsx`;
  }
};

/**
 * 格式化批次名称
 * 1. 移除日期后面的 "_数字" 部分（如：20250924_55 -> 20250924）
 * 2. 去除连续的重复片段（如：农信社-好瑞迪-良庆-好瑞迪 -> 农信社-好瑞迪-良庆）
 * @param batchName 原始批次名称
 * @returns 格式化后的批次名称
 */
const formatBatchName = (batchName: string): string => {
  if (!batchName) return '';

  try {
    // 第一步：移除日期后面的 "_数字" 部分
    // 匹配模式：8位数字_数字 或 8位数字_数字-数字
    let formattedName = batchName.replace(/(\d{8})_\d+(-?\d*)/g, '$1$2');
    
    // 第二步：去除重复的片段（保留第一次出现的）
    // 按 "-" 分割成数组
    const parts = formattedName.split('-');
    const uniqueParts: string[] = [];
    const seenParts = new Set<string>();
    
    // 遍历数组，去除重复的项（保留第一次出现的）
    for (let i = 0; i < parts.length; i++) {
      // 如果当前项之前没有出现过，则添加
      if (!seenParts.has(parts[i])) {
        uniqueParts.push(parts[i]);
        seenParts.add(parts[i]);
      }
    }
    
    // 重新组合成字符串
    formattedName = uniqueParts.join('-');
    
    return formattedName;
  } catch (error) {
    console.error('格式化批次名称失败:', error);
    // 如果格式化失败，返回原始名称
    return batchName;
  }
};

// 复制批次名称
const copyBatchName = async (batchName: string) => {
  try {
    // 使用格式化后的批次名称进行复制
    const formattedBatchName = formatBatchName(batchName);
    await navigator.clipboard.writeText(formattedBatchName);
    message.success(`已复制批次名称: ${formattedBatchName}`);
  } catch (error) {
    console.error('复制失败:', error);
    // 降级方案：使用传统的复制方法
    const textArea = document.createElement('textarea');
    textArea.value = formatBatchName(batchName);
    document.body.appendChild(textArea);
    textArea.select();
    try {
      document.execCommand('copy');
      message.success(`已复制批次名称: ${formatBatchName(batchName)}`);
    } catch (fallbackError) {
      console.error('降级复制也失败:', fallbackError);
      message.error('复制失败，请手动复制');
    }
    document.body.removeChild(textArea);
  }
};

// 初始化加载数据
onMounted(async () => {
  await fetchReviewList();

  // 添加复制按钮的点击事件监听
  setTimeout(() => {
    const copyButtons = document.querySelectorAll('.copy-batch-name-btn');
    copyButtons.forEach(button => {
      button.addEventListener('click', (e) => {
        e.preventDefault();
        e.stopPropagation();
        const batchName = (e.target as HTMLElement).closest('.copy-batch-name-btn')?.getAttribute('data-batch-name') || '';
        if (batchName) {
          copyBatchName(batchName);
        }
      });
    });
  }, 100);
});
</script>

<style scoped>
.review-list-container {
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
}

.header-title h2 {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
}

.date-range-info {
  margin: 0;
  font-size: 14px;
  color: #666;
  font-style: italic;
}

.filter-stats {
  color: #1890ff;
  font-weight: 500;
}

.color-legend {
  display: flex;
  gap: 16px;
  margin-top: 8px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #666;
}

.legend-color {
  width: 12px;
  height: 12px;
  border-radius: 2px;
  border: 1px solid #d9d9d9;
}

.today-pending-audit-color {
  background: linear-gradient(135deg, #fff2e8 0%, #f6ffed 100%);
  border-left: 3px solid #ff7a00;
  position: relative;
}


.today-color {
  background-color: #f6ffed;
  border-left: 3px solid #52c41a;
}

.yesterday-color {
  background-color: #fff7e6;
  border-left: 3px solid #fa8c16;
}

.recent-color {
  background-color: #f0f5ff;
  border-left: 3px solid #1890ff;
}

.older-color {
  background-color: #fafafa;
  border-left: 3px solid #d9d9d9;
}



.table-section {
  margin-top: 24px;
}

.table-wrapper {
  overflow-x: auto;
}

/* 案件数量列样式 */
.case-count-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  text-align: left;
}

.count-item {
  font-size: 12px;
  line-height: 1.4;
  color: #666;
}

.count-item:first-child {
  color: #1890ff;
  font-weight: 500;
}

/* 今日案件行样式 */
:deep(.today-row) {
  background-color: #f6ffed !important;
  border-left: 4px solid #52c41a;
}

:deep(.today-row:hover) {
  background-color: #f0f9ff !important;
}

/* 今日待审核案件行样式 - 特殊高亮 */
:deep(.today-pending-audit-row) {
  background: linear-gradient(135deg, #fff2e8 0%, #f6ffed 100%) !important;
  border-left: 4px solid #ff7a00;
  box-shadow: 0 2px 8px rgba(255, 122, 0, 0.15);
  position: relative;
}

:deep(.today-pending-audit-row:hover) {
  background: linear-gradient(135deg, #ffe7ba 0%, #f0f9ff 100%) !important;
  box-shadow: 0 4px 12px rgba(255, 122, 0, 0.25);
  transform: translateY(-1px);
  transition: all 0.3s ease;
}



/* 昨日案件行样式 */
:deep(.yesterday-row) {
  background-color: #fff7e6 !important;
  border-left: 4px solid #fa8c16;
}

:deep(.yesterday-row:hover) {
  background-color: #fffbe6 !important;
}

/* 近3日案件行样式 */
:deep(.recent-row) {
  background-color: #f0f5ff !important;
  border-left: 4px solid #1890ff;
}

:deep(.recent-row:hover) {
  background-color: #e6f7ff !important;
}

/* 更早案件行样式 */
:deep(.older-row) {
  background-color: #fafafa !important;
  border-left: 4px solid #d9d9d9;
}

:deep(.older-row:hover) {
  background-color: #f5f5f5 !important;
}

/* 无日期案件行样式 */
:deep(.no-date-row) {
  background-color: #fff2f0 !important;
  border-left: 4px solid #ff4d4f;
}

:deep(.no-date-row:hover) {
  background-color: #fff1f0 !important;
}

/* 无效日期案件行样式 */
:deep(.invalid-date-row) {
  background-color: #f9f0ff !important;
  border-left: 4px solid #722ed1;
}

:deep(.invalid-date-row:hover) {
  background-color: #f4f0ff !important;
}

/* 表格行悬停效果优化 */
:deep(.ant-table-tbody > tr:hover > td) {
  background-color: inherit !important;
}

/* 状态选项卡样式 */
.status-tabs {
  margin-bottom: 16px;
}

:deep(.status-tabs .ant-tabs-nav) {
  margin-bottom: 0;
}

:deep(.status-tabs .ant-tabs-tab) {
  padding: 8px 16px;
  margin-right: 8px;
}

:deep(.status-tabs .ant-tabs-tab-active) {
  background-color: #f0f9ff;
  border-radius: 4px;
}

:deep(.status-tabs .ant-tabs-content-holder) {
  padding-top: 16px;
}

/* 复制按钮样式 */
:deep(.copy-batch-name-btn) {
  background: none !important;
  border: none !important;
  cursor: pointer;
  padding: 4px !important;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
  color: #666;
}

:deep(.copy-batch-name-btn:hover) {
  background-color: #f0f0f0 !important;
  color: #1890ff;
  transform: scale(1.1);
}

:deep(.copy-batch-name-btn:active) {
  transform: scale(0.95);
}

:deep(.copy-batch-name-btn svg) {
  width: 14px;
  height: 14px;
  fill: currentColor;
}

/* 案件详情弹框样式 */
.case-detail-modal {
  .batch-info {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #f5f5f5;
    border-radius: 6px;

    h4 {
      margin: 0 0 12px 0;
      color: #1890ff;
      font-size: 16px;
    }

    p {
      margin: 8px 0;
      font-size: 14px;
      color: #666;

      strong {
        color: #333;
        margin-right: 8px;
      }
    }
  }

  .user-list {
    box-sizing: border-box;
    padding: 16px;

    h4 {
      margin: 0 0 16px 0;
      color: #1890ff;
      font-size: 16px;
    }
  }
}

/* 客户信息样式 */
.client-info {
  text-align: left;

  .client-name {
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
  }

  .client-mobile,
  .client-id-card {
    font-size: 12px;
    color: #666;
    margin-bottom: 2px;
  }
}

/* 金融资产样式 */
.financial-assets {
  text-align: left;

  .delegate-amount,
  .current-amount {
    font-size: 12px;
    margin-bottom: 2px;
  }

  .delegate-amount {
    color: #ff4d4f;
    /* 红色 */
    font-weight: 500;
  }

  .current-amount {
    color: #666;
  }
}

/* 查看/审核按钮样式 */
:deep(.view-audit-btn.ant-btn-link) {
  position: relative !important;
  transition: all 0.3s ease !important;
  border-radius: 4px !important;
  padding: 4px 8px !important;
  font-weight: 500 !important;
  border: none !important;
}

:deep(.view-audit-btn.ant-btn-link:hover) {
  background-color: #e6f7ff !important;
  color: #1890ff !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2) !important;
  border: none !important;
}

:deep(.view-audit-btn.ant-btn-link:active) {
  background-color: #bae7ff !important;
  color: #0050b3 !important;
  transform: translateY(0) !important;
  box-shadow: 0 1px 4px rgba(24, 144, 255, 0.3) !important;
  border: none !important;
}

/* 已查看状态 */
:deep(.view-audit-btn.viewed.ant-btn-link) {
  color: #52c41a !important;
  background-color: #f6ffed !important;
  border: 1px solid #b7eb8f !important;
}

:deep(.view-audit-btn.viewed.ant-btn-link:hover) {
  background-color: #d9f7be !important;
  color: #389e0d !important;
  border-color: #95de64 !important;
}

/* 下载摘要按钮样式 */
:deep(.download-summary-btn.ant-btn-link) {
  position: relative !important;
  transition: all 0.3s ease !important;
  border-radius: 4px !important;
  padding: 4px 8px !important;
  font-weight: 500 !important;
  border: none !important;
}

:deep(.download-summary-btn.ant-btn-link:hover) {
  background-color: #fff7e6 !important;
  color: #fa8c16 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 2px 8px rgba(250, 140, 22, 0.2) !important;
  border: none !important;
}

:deep(.download-summary-btn.ant-btn-link:active) {
  background-color: #ffd591 !important;
  color: #d46b08 !important;
  transform: translateY(0) !important;
  box-shadow: 0 1px 4px rgba(250, 140, 22, 0.3) !important;
  border: none !important;
}

/* 已下载状态 */
:deep(.download-summary-btn.downloaded.ant-btn-link) {
  color: #722ed1 !important;
  background-color: #f9f0ff !important;
  border: 1px solid #d3adf7 !important;
}

:deep(.download-summary-btn.downloaded.ant-btn-link:hover) {
  background-color: #efdbff !important;
  color: #531dab !important;
  border-color: #b37feb !important;
}
</style>